package com.copm.demonstrationsystem.service.introductionfeatures.impl;

import com.copm.demonstrationsystem.commons.response.ResponseStatus;
import com.copm.demonstrationsystem.config.SystemConfig;
import com.copm.demonstrationsystem.dao.commons.ImageDao;
import com.copm.demonstrationsystem.dao.introductionfeatures.FacilityPageDao;
import com.copm.demonstrationsystem.dao.introductionfeatures.landscape.LandscapeTypeImageDao;
import com.copm.demonstrationsystem.dao.introductionfeatures.landscape.PlaceTypeDao;
import com.copm.demonstrationsystem.dto.introductionfeatures.landscapeAndFacility.*;
import com.copm.demonstrationsystem.pojo.commons.Image;
import com.copm.demonstrationsystem.pojo.introductionfeatures.FacilityPage;
import com.copm.demonstrationsystem.pojo.introductionfeatures.landscape.LandscapeTypeImage;
import com.copm.demonstrationsystem.pojo.introductionfeatures.landscape.PlaceType;
import com.copm.demonstrationsystem.service.introductionfeatures.FacilityService;
import com.copm.demonstrationsystem.service.introductionfeatures.LandscapeService;
import com.copm.demonstrationsystem.service.introductionfeatures.commons.MultiImageAndTextHandle;
import com.copm.demonstrationsystem.service.introductionfeatures.commons.SinglonImageHandle;
import com.copm.demonstrationsystem.service.introductionfeatures.commons.TransformImagePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Yuan Baiyu
 * @Date: Created in 15:11 2018/4/23
 */
@Service
public class LandscapeServiceImpl implements LandscapeService {

    private Logger logger = LoggerFactory.getLogger(LandscapeServiceImpl.class);

    @Autowired
    private SystemConfig config;

    @Autowired
    LandscapeTypeImageDao landscapeTypeImageDao;

    @Autowired
    FacilityPageDao facilityPageDao;

    @Autowired
    PlaceTypeDao placeTypeDao;

    @Autowired
    FacilityService facilityService;

    @Autowired
    ImageDao imageDao;

    @Autowired
    MultiImageAndTextHandle multiImageAndTextHandle;

    @Autowired
    SinglonImageHandle singlonImageHandle;

    @Autowired
    TransformImagePath transformImagePath;

    //1.0、获取园林景观接口，包括里面的所有的图片
    public ResponseStatus getLandscapeTypes() {
        ResponseStatus status = new ResponseStatus();
        FacilityPage facilityPage = facilityPageDao.findPage();
        PlaceType placeType;
        String name;
        String toUrl;
        //最终响应对象（包括园林景观、周边设施）
        ParkAndNearDto parkAndNearDto = new ParkAndNearDto();
        //园林景观页面对象
        LandscapeDto landscapeDto = new LandscapeDto();
        //周边设施页面对象
        NearDto nearDto = new NearDto();

        name = "园林景观";

        landscapeDto.setName(name);
        landscapeDto.setToUrl(facilityPage.getParkToUrl());
        //查找公共设施的图片
        List<LandscapeTypeImage> commons = landscapeTypeImageDao.findByImageKind(1L);
        int commons_size = commons.size();
        //创建公共施设图片响应对象集合
        List<LandscapeCommon> landscapeCommons = new ArrayList<>(commons_size);
        for (LandscapeTypeImage c : commons) {
            Image image = c.getImage();
            if (null == image) {
                continue;
            }
            transformImagePath.transformImagePath(image);
            //根据地址类型id查询地址类型对象
            if (null == c.getPlaceTypeId()) {
                logger.info("Landscape 页面" + c + "无法查询地址类型");
                landscapeCommons.add(new LandscapeCommon(c, null));
            } else {
                placeType = placeTypeDao.findOne(c.getPlaceTypeId());
                if (null == placeType) {
                    logger.info("图片无地址类型");
                    landscapeCommons.add(new LandscapeCommon(c, null));
                }
                landscapeCommons.add(new LandscapeCommon(c, placeType.getName()));
            }
        }

        //查找园林景观的图片
        List<LandscapeTypeImage> parks = landscapeTypeImageDao.findByImageKind(2L);
        int parks_size = parks.size();
        //创建园林景观图片响应对象集合
        List<LandscapePark> landscapeParks = new ArrayList<>(parks_size);
        //遍历公共设施图片并 响应格式化
        for (LandscapeTypeImage p : parks) {
            if (null == p) {
                logger.info("Landscape 页面" + p + "无法查询");
                continue;
            }

            Image image = p.getImage();
            if (null == image) {
                continue;
            }
            transformImagePath.transformImagePath(image);
            if (null == p.getPlaceTypeId()) {
                logger.info("Landscape 页面" + p + "无法查询地址类型");
                landscapeParks.add(new LandscapePark(p, null));
            } else {
                //根据地址类型id查询地址类型对象
                placeType = placeTypeDao.findOne(p.getPlaceTypeId());
                if (null == placeType) {
                    logger.info("图片无地址类型");
                    landscapeParks.add(new LandscapePark(p, null));
                }
                landscapeParks.add(new LandscapePark(p, placeType.getName()));
            }
        }
        landscapeDto.setCommon(landscapeCommons);
        landscapeDto.setPark(landscapeParks);

        nearDto.setName("周边设施");
        nearDto.setToUrl(facilityPage.getNearToUrl());

        if (null == facilityPage.getImage()) {
            nearDto.setUrl(null);
        } else {
            //因为返回转化的格式设计原因，无法通过调用图片路径转化的工具类实现，暂时只能通过硬编码实现效果。
            nearDto.setUrl("http://" + config.getServerIp() + ":" + config.getServerPort() + "/" + config.getApplicationName() + "/image/" + facilityPage.getImage().getFileName());
            nearDto.setMiddle("http://" + config.getServerIp() + ":" + config.getServerPort() + "/" + config.getApplicationName() + "/image/" + facilityPage.getImage().getMiddle());
            nearDto.setMin("http://" + config.getServerIp() + ":" + config.getServerPort() + "/" + config.getApplicationName() + "/image/" + facilityPage.getImage().getMin());
        }

        parkAndNearDto.setLandscapeDto(landscapeDto);
        parkAndNearDto.setNearDto(nearDto);
        //设置返回数据
        status.setData(parkAndNearDto);
        status.setStatue(1);
        logger.info("Landscape 页面查询成功！");
        return status;
    }

    //1.1、位置类型添加接口
    public ResponseStatus addPlaceType(String name) {
        ResponseStatus status = new ResponseStatus();
        status.setStatue(0);

        //判断该房间类型是否已经存在
        PlaceType placeType = placeTypeDao.findByName(name);

        //如果该房间类型不存在
        if (null == placeType) {
            //添加一个新的户型
            placeType = new PlaceType(name);
            try {
                placeTypeDao.save(placeType);
                //返回状态为正常
                status.setStatue(1);
                logger.info("添加新的位置类型：" + name + " 成功！");
            } catch (Exception e) {
                logger.error("添加新的位置类型：" + name + " 失败！");
                status.setMessage("数据存储出错");
            }
        } else {
            logger.info("添加的位置类型：" + name + " 已经存在！");
            status.setMessage("这个位置类型已经存在了");
        }
        logger.info("Landscape 位置类型添加成功！");
        return status;
    }

    //1.2、位置类型删除接口
    @Transactional
    public ResponseStatus deletePlaceType(Long id) {

        ResponseStatus status = new ResponseStatus();
        status.setStatue(0);
        List<LandscapeTypeImage> lists = landscapeTypeImageDao.findByPlaceTypeId(id);
        System.out.println(lists);
        for (LandscapeTypeImage landscapeTypeImage : lists) {
            if (null != landscapeTypeImage) {
                landscapeTypeImageDao.deleteByPlaceTypeId(id);
            }
        }
        try {
            placeTypeDao.delete(id);
            //返回状态正常
            status.setStatue(1);
        } catch (Exception e) {
            logger.info("删除位置类型：" + id + " 失败！");
            status.setMessage("删除位置类型失败");
        }
        status.setStatue(1);
        logger.info("Landscape 位置类型删除成功");
        return status;
    }

    //1.3、获取全部位置类型接口
    public ResponseStatus getPlaceTypes() {
        ResponseStatus status = new ResponseStatus();
        status.setStatue(0);

        try {
            List<PlaceType> placeTypes = placeTypeDao.findAll();
            boolean empty = placeTypes == null || placeTypes.size() == 0;
            if (empty) {
                status.setMessage("还没有位置类型");
            } else {
                status.setData(placeTypes);
                status.setStatue(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            status.setMessage("获取位置类型失败");
        }
        logger.info("Landscape 获取全部位置类型成功！");
        return status;
    }


    //3.1、图片添加接口
    public ResponseStatus addLandscapeTypeImage(LandscapeTypeImageReceiveDto imageReceiveDto, MultipartFile file) {
        ResponseStatus status = singlonImageHandle.storeAndCheckImage(file);
        if (0 == status.getStatue()) {
            return status;
        }
        //选取图片的位置类型
        PlaceType placeType = placeTypeDao.findOne(imageReceiveDto.getplaceTypeId());

        //获取图片存储信息
        String[] paths = (String[]) status.getData();
        Image image = new Image(paths[0], paths[1], paths[2]);

        //存储这个图片的记录
        LandscapeTypeImage houseTypeImage = new LandscapeTypeImage(
                imageReceiveDto.getplaceTypeId(), imageReceiveDto.getKind(), image);

        landscapeTypeImageDao.save(houseTypeImage);
        status.setStatue(1);
        logger.info("Landscape 页面图片添加成功");
        return status;
    }

    //3.2、图片删除接口
    public ResponseStatus deleteLandscapeTypeImage(Long id) {
        Image image = imageDao.findOne(id);
        //外键查找待删除的图片数据
        LandscapeTypeImage landscapeTypeImage = landscapeTypeImageDao.findByImage_Id(id);
        ResponseStatus status = singlonImageHandle.deleteImage(image);
        if (0 == status.getStatue()) {
            return status;
        }
        //删除记录
        landscapeTypeImageDao.delete(landscapeTypeImage);

        status.setStatue(1);
        logger.info("Landscape 页面图片删除成功");
        return status;
    }

    @Override
    public ResponseStatus modifyLandscapeToUrl(String toUrl) {
        //因为"园林景观"的toUrl数据库字段放在了Facility对象中
        ResponseStatus status = new ResponseStatus();
        //查询“周边设施”页面（只有一个页面数据）
        FacilityPage facilityPage = facilityPageDao.findPage();
        if (null == facilityPage) {
            //新建“周边设施”页面对象
            facilityPage = new FacilityPage();
        }
        //设置页面对象
        facilityPage.setParkToUrl(toUrl);
        //保存页面对象
        facilityPageDao.save(facilityPage);
        status.setStatue(1);
        logger.info("Landscape页面 toUrl 修改成功！");
        return status;
    }
}
